import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: yang
 * Date: 2022-09-05
 * Time: 20:04
 */
public class ThreadSum {
    public static void main(String[] args) throws InterruptedException {
        int[] arr = new int[1000_0000_0];
        for (int i = 0; i < arr.length; i++) {
            Random random = new Random();
            arr[i] = random.nextInt(100)+1;
        }

        //单线程求和
        long start = System.currentTimeMillis();
        long sum = 0;
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
        }

        System.out.println(sum);
        long end = System.currentTimeMillis();
        System.out.println("单线程耗时" + (end - start) + "ms");



        //多线程求和
        SumOperator operator = new SumOperator();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < arr.length; i+=2) {
                operator.evenSum(arr[i]);
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 1; i < arr.length; i+=2) {
                operator.oddSum(arr[i]);
            }
        });

        start = System.currentTimeMillis();

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println(operator.even + operator.odd);
        end = System.currentTimeMillis();
        System.out.println("多线程耗时" + (end - start) + "ms");
    }
}

class SumOperator{
    public long odd = 0;
    public long even = 0;
    public void oddSum(int num){
        odd += num;
    }

    public void evenSum(int num){
        even += num;
    }
}
